<template>
  <div class="event-info">
    <el-form :model="ruleForm" :rules="rules" ref="UserForm" label-width="100px" label-suffix="：">
      <div class="event-content">
        <el-form-item label="角色" prop="roleId">
          <div class="cont-input">
            <el-select v-model="ruleForm.roleId" placeholder="请选择">
              <el-option
                v-for="item in roleData"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="用户名" prop="memberName">
          <div class="cont-input">
            <el-input v-model="ruleForm.memberName" placeholder="请输入用户名"></el-input>
          </div>
        </el-form-item>
        <template v-if="commonTabInfo.text === '新增用户'">
          <el-form-item label="密码" prop="passwords">
            <div class="cont-input">
              <el-input v-model="ruleForm.passwords" type="password" placeholder="请输入密码"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="确认密码" prop="secPasswords">
            <div class="cont-input">
              <el-input v-model="ruleForm.secPasswords" type="password" placeholder="请再次输入密码"></el-input>
            </div>
          </el-form-item>
        </template>
        <el-form-item label="手机" prop="mobile">
          <div class="cont-input">
            <el-input v-model="ruleForm.mobile" placeholder="请输入手机"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <div class="cont-input">
            <el-input v-model="ruleForm.email" placeholder="请输入邮箱"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="isActivity">
          <div class="cont-input">
            <el-switch
              v-model="ruleForm.isActivity"
              active-value="1"
              inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </div>
        </el-form-item>
      </div>
      <div class="cont-footer">
        <el-button @click.native="eventTab('', 'first' )">取消</el-button>
        <template v-if="commonTabInfo.text === '新增用户'">
          <el-button type="primary" @click.native="addUserEvent">保存</el-button>
        </template>
        <template v-else-if="commonTabInfo.text === '编辑用户'">
          <el-button type="primary" @click.native="editUserEvent">保存编辑</el-button>
        </template>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { AddUser, GetUserSingle, UpdateUser, GetRoleTable } from '@/api/requestConfig'
  export default {
    name: 'UserInfo',
    data() {
      // 手机号验证规则
      var phoneReg = (rule, value, callback) => {
        if (rule.required) {
          if (value === '') {
            callback(new Error('请输入手机号'))
          }
        }
        if (value) {
          if (!(/^1[3456789]\d{9}$/.test(value))) {
            callback(new Error('请输入格式正确的手机号'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      // 邮箱验证规则
      var emailReg = (rule, value, callback) => {
        if (rule.required) {
          if (value === '') {
            callback(new Error('请输入邮箱'))
          }
        }
        if (value) {
          if (!(/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value))) {
            callback(new Error('请输入格式正确的邮箱'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }

      var passwordsReg = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else if (value.length < 3) {
          callback(new Error('密码不得小于三位数'))
        } else {
          if (this.ruleForm.secPasswords !== '') {
            this.$refs.UserForm.validateField('secPasswords')
          }
          callback()
        }
      }
      var secPasswordsReg = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value.length < 3) {
          callback(new Error('密码不得小于三位数'))
        } else if (value !== this.ruleForm.passwords) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        roleData: [],
        ruleForm: {
          isActivity: '1',
          memberName: '',
          roleId: [],
          mobile: '',
          passwords: '',
          secPasswords: '',
          email: ''
        },
        rules: {
          memberName: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
          roleId: [
            { required: true, message: '请选择角色', trigger: 'change' }
          ],
          passwords: [
            { required: true, validator: passwordsReg, trigger: 'blur' }
          ],
          secPasswords: [
            { required: true, validator: secPasswordsReg, trigger: 'blur' }
          ],
          mobile: [
            { required: false, type: 'number', validator: phoneReg, trigger: 'blur' }
          ],
          email: [
            { required: false, validator: emailReg, trigger: 'blur' }
          ]
        },
        editData: {},
        addFlag: true
      }
    },
    computed: {
      ...mapGetters([
        'commonTabInfo'
      ])
    },
    created() {
      // 获取所有的角色列表
      var needData = {
        pageSize: 1000,
        curPage: 1,
        isActivity: '1'
      }
      GetRoleTable(needData).then(res => {
        if (res.data) {
          this.roleData = res.data
        } else {
          this.$message.error(res.message)
        }
        this.tableLoading = false
      }).then(() => {
        // 编辑时获取数据
        if (this.commonTabInfo.text === '编辑用户') {
          GetUserSingle(this.commonTabInfo.custom.id).then(res => {
            if (res.data) {
              const resData = res.data
              this.editData = resData
              if (this.editData) {
                for (var key in this.editData) {
                  if (key === 'isActivity') {
                    this.ruleForm[key] = String(this.editData[key])
                  } else {
                    this.ruleForm[key] = this.editData[key]
                  }
                }
                this.ruleForm.secPasswords = this.ruleForm.passwords
              }
            }
          })
        }
      })
    },
    methods: {
      // tabs操作
      eventTab(text, tabsName, custom) {
        this.$store.dispatch('handleTabInfo', {
          text: text,
          tabsName: tabsName,
          custom: custom
        })
      },
      // 新增用户
      addUserEvent() {
        var self = this
        if (!this.addFlag) {
          return
        }
        this.$refs.UserForm.validate(function(valid) {
          if (valid) {
            var needData = {}
            needData.roleId = self.ruleForm.roleId
            var userData = {}
            userData.memberName = self.ruleForm.memberName
            userData.passwords = self.ruleForm.passwords
            userData.email = self.ruleForm.email
            userData.mobile = self.ruleForm.mobile
            userData.isActivity = self.ruleForm.isActivity
            needData.dfyzWebsiteUserInfo = userData
            self.addFlag = false
            AddUser(needData).then(res => {
              if (res.code === 200) {
                self.$message.success(res.message)
                setTimeout(function() {
                  self.eventTab('refresh', 'first', 'user')
                }, 500)
              } else {
                self.$message.error(res.message)
              }
            }).catch(error => {
              console.log(error)
            })
          } else {
            return
          }
        })
        setTimeout(function() {
          self.addFlag = true
        }, 3000)
      },
      // 编辑
      editUserEvent() {
        var self = this
        if (!this.addFlag) {
          return
        }
        this.$refs.UserForm.validate(function(valid) {
          if (valid) {
            var needData = {}
            needData.roleId = self.ruleForm.roleId
            var userData = {}
            userData.id = self.editData.id
            userData.memberName = self.ruleForm.memberName
            userData.email = self.ruleForm.email
            userData.mobile = self.ruleForm.mobile
            userData.isActivity = self.ruleForm.isActivity
            needData.dfyzWebsiteUserInfo = userData
            self.addFlag = false
            UpdateUser(needData).then(res => {
              if (res.code === 200) {
                self.$message.success(res.message)
                setTimeout(function() {
                  self.eventTab('update', 'first', 'user')
                }, 500)
              } else {
                self.$message.error(res.message)
              }
            }).catch(error => {
              console.log(error)
            })
          } else {
            return
          }
        })
        setTimeout(function() {
          self.addFlag = true
        }, 3000)
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  @import "src/styles/info.scss";
</style>
